// Based loosely around work by Witold Szczerba - https://github.com/witoldsz/angular-http-auth
angular.module('security.service', [
  'security.retryQueue'    // Keeps track of failed requests that need to be retried once the user logs in
  , 'COMMON_DEFINE' // 引入常量
])
.factory('security', ['$http', '$q', '$location', '$state', 'securityRetryQueue', 'ROOT_STATE_NAME', function($http, $q, $location, $state, queue, ROOT_STATE_NAME) {

	// Register a handler for when an item is added to the retry queue
	queue.onItemAddedCallbacks.push(function(retryItem) {
		if ( queue.hasMore() ) {
            $state.go(ROOT_STATE_NAME);
		}
	});

	// The public API of the service
	var service = {
		// Get the first reason for needing a login
		getLoginReason: function() {
			return queue.retryReason();
	    },

		// Attempt to authenticate a user by the given email and password
		login : function (username, password) {
			var postCfg = {
		           headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		    };
			var data = "username=" + username + "&password=" + password;
			var request = $http.post('/authenticate', data, postCfg);
			return request.then(function(response) {
                var tempData = response.data == 'login:failure' ? null : response.data;
				service.currentUser = tempData;
				if ( service.isAuthenticated() ) {
					// 存放sessionID
					sessionStorage.setItem('user', response.data);
				}
				return service.isAuthenticated();
			});
		},

        // Logout the current user and redirect
        logout: function() {
            return $http.post('/logout').then(function() {
                service.currentUser = null;
                return service.currentUser;
            });
        },

		// Ask the backend to see if a user is already authenticated - this may be from a previous session.
		requestCurrentUser : function () {
			return $http.get('/getuser').then(function (res) {
				var reqData = res.data
					, username = reqData.username;
				
				if (username != 'Guest') { // 登录
					service.currentUser = reqData
				} else { // 未登录
					service.currentUser = null;
				}
				return service.currentUser;
			});
		},

    	// Information about the current user
    	currentUser: null,

		// Is the current user authenticated?
		isAuthenticated: function () {
			return !!service.currentUser;
		}
  //  
  //  // Is the current user an adminstrator?
  //  isAdmin: function() {
  //    return !!(service.currentUser && service.currentUser.admin);
  //  }
	};

	return service;
}]);
